<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat, toYuan, copyToCliboard, timeFormat_2 } from '@/hooks/util'
import * as userListApi from '@/api/userList'
import * as accountApi from '@/api/account'
import orderModal from './orderModal.vue'
import Modal from '@/components/Modal/index.vue'
import Channel from './channel.vue'
import CountdownTime from './timer.vue'
import * as orderApi from '@/api/order'
import { message } from 'ant-design-vue'
const route = useRoute()
const ChongMoneyRef = ref()
const rechargeRef = ref()
interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper?: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  // console.log(page, pageSize)
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  orderNumber?: string | number
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
  channel: 3,
})

const dataSource = ref([])
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 400,
  },
  {
    title: '电影海报',
    key: 'filmImg',
    width: 200,
  },
  {
    title: '电影名称',
    key: 'filmName',
    width: 300,
  },
  {
    title: '影院信息',
    key: 'filmData',
    width: 400,
  },
  {
    title: '座位信息',
    key: 'SeatData',
    width: 400,
  },
  {
    title: '价格信息',
    key: 'price',
    width: 400,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    align: 'center',
  },
]

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  searchParams.value.orderNumber = ''
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await orderApi.getOwnOutTicketList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

onMounted(() => getList())

import type { SelectProps } from 'ant-design-vue'
const orderStatusList = ref<SelectProps['options']>([
  {
    label: '待出票',
    value: 1,
  },
  {
    label: '已完成',
    value: 2,
  },
  {
    label: '已关闭',
    value: 3,
  },
])
const userGroupList = ref<SelectProps['options']>([
  {
    label: 'ADMIN',
    value: 1,
  },
  {
    label: 'USER',
    value: 0,
  },
])

const formRef = ref()
interface FormState {
  orderNumber?: string
  userGroup?: number
  state?: number
  [propName: string]: any
}
const formState = reactive<FormState>({})

// 查询
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  searchParams.value.orderNumber = formState.orderNumber

  getList()
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.resetFields()
  for (let key in searchParams.value) {
    if (key != 'currentPage' && key != 'pageSize')
      searchParams.value.hasOwnProperty(key) && delete searchParams.value[key]
  }
  getList()
}

const chongMoney = (id: string) => {
  ChongMoneyRef.value.showModal(id)
}

// 复制规则
const copyRule = (record: any) => {
  copyToCliboard(`您的票达人账号：${record.userName}已充值，当前余额：${toYuan(record.balance)}元`)
  // message.success('复制成功')
}

const recharge = (id: string) => {
  console.log('充值')
  rechargeRef.value.showModal(id)
}
const orderDetailModelRef = ref(null)

const orderDetailModelRefOpen = (record: any) => {
  orderDetailModelRef.value.showModal(record)
}
const cancelOrderInfo = ref({})
const cancelModalRef = ref(null)
const reason = ref('')
const cancelOrder = async (record: any) => {
  cancelOrderInfo.value = record
  cancelModalRef.value.setVisible(true)
  //  try{
  //    const result =await orderApi.cancelFilmOrder({
  //     orderId:record.id,
  //     reason:''
  //    })
  //  }catch(err){
  //   message.error('取消订单失败，请重新尝试~')
  //  }
}

//支付出票
const PayModelRefOpen = record => {
  itemInfo.value = record
  open.value = true
  PerformLoop(record.taskId)

  // PayModelRef.value.showModal(record)
}
const cancelByconfirm = async () => {
  try {
    const result = await orderApi.cancelFilmOrder({
      orderId: cancelOrderInfo.value.id,
      reason: reason.value,
    })
    if (result.state == 200) {
      message.success('取消订单成功~')
      getList()
      cancelModalRef.value.setVisible(false)
    } else {
      message.error(result.message)
    }
  } catch (err) {
    message.error('取消订单失败，请重新尝试~')
  }
}

const PreviewModal = (list: any) => {
  imgViewRef.value.showModal(list)
}

const open = ref(false) // 支付出票 - 弹窗

const checked = ref(true) // 限价的选中状态
const disabled = ref(false) // 是否禁用限价

const confirmLoading = ref(false) //加载中

// 渠道
const chanelList = ref([
  {
    id: 88,
    name: '芒果电影票',
    icon: 'http://h5.liangpiao.net.cn/logo/1.jpg',
    desc: '预估限价',
    isSupport: 1,
    selectNum: 1,
    time: 0,
    text: '支持限价，你的出票成本=供应商中标价+供应商中标价*3%，手续费为供应渠道收取，良票平台不收取任何订单手续费',
    isCan: 0,
  },
  {
    id: 66,
    name: '芒果一口价',
    icon: 'http://h5.liangpiao.net.cn/logo/1.jpg',
    desc: '一口价',
    isSupport: 0,
    selectNum: 0,
    time: 0,
    text: '你的出票成本=预估出票价',
    isCan: 0,
  },
  // //渠道
  // {
  //   id: 5,
  //   name: '芒果电影票（一口价）',
  //   icon: 'http://h5.liangpiao.net.cn/logo/1.jpg',
  //   text: '出票成本=预估出票价',
  //   isSupport: 0,
  //   selectNum: 1,
  //   desc: '出票成本',
  //   isCan: 0,
  // },
  {
    id: 3,
    name: '麻花电影票（可限价）',
    icon: 'http://h5.liangpiao.net.cn/logo/maHua.jpg',
    text: '支持限价，你的出票成本=供应商中标价+供应商中标价*3%，手续费为供应渠道收取，票达人平台不收取任何订单手续费',
    isSupport: 1,
    selectNum: 0, // 1：主，2：备
    desc: '预估出票价',
    isCan: 0,
  },
  {
    id: 11,
    name: '守兔电影票（一口价）',
    icon: 'http://h5.liangpiao.net.cn/logo/2.jpg',
    text: '你的出票成本=预估出票价',
    isSupport: 0,
    selectNum: 0, // 选中的备渠道
    desc: '出票成本',
    isCan: 0,
  },
  {
    id: 7,
    name: '守兔电影票（可限价）',
    icon: 'http://h5.liangpiao.net.cn/logo/2.jpg',
    text: '支持限价，你的出票成本=供应商中标价+供应商中标价*3%，手续费为供应渠道收取，票达人平台不收取任何订单手续费',
    isSupport: 1,
    selectNum: 0,
    desc: '预估出票价',
    isCan: 0,
  },
  {
    id: 10,
    name: '影划算电影票（可限价）',
    icon: 'http://h5.liangpiao.net.cn/logo/ying.png',
    text: '支持限价，你的出票成本=供应商中标价+供应商中标价*3%，手续费为供应渠道收取，票达人平台不收取任何订单手续费',
    isSupport: 1,
    selectNum: 0,
    desc: '预估出票价',
    isCan: 0,
  },
  {
    id: 8,
    name: '星驰电影票（一口价）',
    icon: 'http://h5.liangpiao.net.cn/logo/xingChi.jpg',
    text: '你的出票成本=预估出票价',
    isSupport: 1,
    selectNum: 0,
    desc: '出票成本',
    isCan: 1,
  },
  {
    id: 6,
    name: '哈哈电影票',
    icon: 'http://h5.liangpiao.net.cn/logo/3.jpg',
    text: '不支持限价，你的出票成本=供应商中标价+原价*3%，手续费为供应渠道收取，票达人平台不收取任何订单手续费',
    isSupport: 0,
    selectNum: 0,
    desc: '预估出票价',
    isCan: 1,
  },
  {
    id: 9,
    name: '哈哈电影快票（固定9折）',
    icon: 'http://h5.liangpiao.net.cn/logo/3.jpg',
    text: '你的出票成本=猫淘价（原价）*90%',
    isSupport: 0,
    selectNum: 0,
    desc: '出票成本',
    isCan: 1,
  },
])

// 当前选中的渠道
const selectedChannelList = ref([])

let limitPriceSwitchFlag = ref(false)

// 弹框取消操作
const cancel = () => {
  open.value = false
}

const itemInfo = ref({}) // 点击支付出票，数据

// 打开，支付出票的弹框
const getDraw = (item: any) => {
  itemInfo.value = item
  selectedChannelList.value = [] // 每次都变成空数组

  open.value = true // 打开，支付出票的弹框

  PerformLoop(item.taskId)
}

// 循环调用获取 当前预报价的接口
const PerformLoop = async (id: any) => {
  for (const role of chanelList.value) {
    if (role.id != 7) {
      await performTask(role, id)
    }
  }
}

// 获取预报价的接口
const performTask = async (item: any, id: any) => {
  try {
    const result = await accountApi.getChaYu({ taskId: id, ticketChannel: item.id })
    if (result.state == 200) {
      if (result.data.price > 0) {
        item.netPrice = result.data.price
      }
    } else if (result.message == '操作频繁') {
      item.netPrice = 0
    }
    // 想把哪个 渠道默认选中主渠道 就需要 将这个id 判断一下 添加进当前的数组   主渠道 需要添加数组第一个 备渠道需要添加进数组第二个   当前的代码是默认添加了一个主渠道
    if (item.id == 88) {
      selectedChannelList.value.push(item)
    }

    // if (item.id == 11) {
    //   selectedChannelList.value.push(item)
    // }
  } catch (err) {
    performTask(item, id)
  }
}

// 获取当前选中的渠道
const getSelectedChannel = (e: any) => {
  selectedChannelList.value = e // 当前选择的值
  console.log('selectedChannelList=', selectedChannelList.value)

  // 判断当前的是否限价开关 禁用 和 关闭 判断
  checked.value = selectedChannelList.value.some(item => item.isSupport == 1)
  disabled.value = selectedChannelList.value.every(item => item.isSupport == 0)
  console.log('disabled.value=', disabled.value)
}

// 支付出票弹框 - 确定按钮
const handleOk = async () => {
  confirmLoading.value = true
  if (selectedChannelList.value.length < 1) {
    // message.warning('主备渠道必须选择~')
    message.warning('请选择渠道~')
    confirmLoading.value = false
    return
  }

  let params = {
    orderId: itemInfo.value.id,
    matchChannel: selectedChannelList.value[0].id,
    slaveMatchChannel: selectedChannelList.value[1].id,
    enableLimitPrice: checked.value ? 1 : 0,
  }

  if (selectedChannelList.value.length == 2) {
    params.slaveMatchChannel = selectedChannelList.value[1].id
  } else {
    params.slaveMatchChannel = 0
  }

  try {
    const res = await orderApi.submitFilmPayOrder(params)
    if (res.state === 200) {
      message.success('支付出票成功~')
      confirmLoading.value = false
      open.value = false
    } else {
      message.error(res.message)
      confirmLoading.value = false
    }
  } catch {
    confirmLoading.value = false
  }
}

// 计算结束时间（创建时间 + 28分钟）
const getEndTime = (createTime: any) => {
  return new Date(Number(createTime) + 28 * 60 * 1000)
}

// 格式化日期
const formatDate = timestamp => {
  return new Date(timestamp).toLocaleString()
}

// 处理倒计时过期事件
const handleExpired = id => {
  console.log(`项目 ${id} 已过期`)
  // 可以在这里更新状态或执行其他操作
}
</script>

<template>
  <a-card style="overflow-x: scroll" :bordered="false">
    <Modal
      ref="cancelModalRef"
      title="确定取消放单"
      :width="600"
      :height="500"
      @on-confirm-add="cancelByconfirm"
    >
      <template #contentValue>
        <div class="cancel-ipt-container">
          <div class="cancel-ipt-item">取消原因：</div>
          <a-input
            v-model:value="reason"
            placeholder="请输入取消原因(可选填)"
            style="width: 300px"
          ></a-input>
        </div>
      </template>
    </Modal>

    <a-modal
      v-model:open="open"
      centered
      title="支付出票"
      @ok="handleOk"
      @cancel="cancel"
      :width="1100"
      :maskClosable="false"
      :confirmLoading="confirmLoading"
    >
      <div class="pay-modal">
        <div class="imgUrl">
          <a-image :width="200" :src="itemInfo?.identifyImg" />
        </div>

        <div class="info-data">
          <a-descriptions bordered size="middle" :column="1" :span="8">
            <a-descriptions-item label="城市">{{ itemInfo.city || '-' }}</a-descriptions-item>
            <a-descriptions-item label="院线">{{ itemInfo.lineName || '-' }}</a-descriptions-item>
            <a-descriptions-item label="影院名称">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ itemInfo.cinemaName }}</span>
                </template>
                <span class="hiddenText">{{ itemInfo.cinemaName }}</span>
              </a-tooltip>
            </a-descriptions-item>
            <a-descriptions-item label="影院地址">
              <a-tooltip placement="top">
                <template #title>
                  {{ itemInfo.cinemaAddress || '-' }}
                </template>
                <span class="hiddenText">{{ itemInfo.cinemaAddress || '-' }}</span>
              </a-tooltip>
            </a-descriptions-item>
            <a-descriptions-item label="影片">
              <a-tooltip placement="top">
                <template #title>
                  {{ itemInfo.filmName || '-' }}
                </template>
                <span class="hiddenText">{{ itemInfo.filmName || '-' }}</span>
              </a-tooltip>
            </a-descriptions-item>
            <a-descriptions-item label="影厅">
              <a-tooltip placement="top">
                <template #title>
                  {{ itemInfo.showName || '-' }}
                </template>
                <span class="hiddenText">{{ itemInfo.showName || '-' }}</span>
              </a-tooltip>
            </a-descriptions-item>
            <a-descriptions-item label="放映时间">
              {{ timeFormat(itemInfo.showTime) || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="座位">
              <a-tooltip placement="top">
                <template #title>
                  <span
                    v-if="itemInfo?.seatNos"
                    v-for="item in itemInfo?.seatNos.split(',')"
                    :key="item"
                  >
                    {{ item }}
                    <span v-if="item.changeStatus == 0">未换座</span>
                    <span v-if="item.changeStatus == 1">已换座</span>
                  </span>
                </template>
                <span class="hiddenText" style="position: relative; top: 4px">
                  <a-tag
                    style="line-height: 16px"
                    v-if="itemInfo?.seatNos"
                    v-for="item in itemInfo?.seatNos.split(',')"
                    :key="item"
                  >
                    {{ item }}
                    <span v-if="item.changeStatus == 0">未换座</span>
                    <span v-if="item.changeStatus == 1">已换座</span>
                  </a-tag>
                </span>
              </a-tooltip>
            </a-descriptions-item>
          </a-descriptions>
        </div>

        <div class="channel-box">
          <Channel
            :tabList="chanelList"
            :selectedChannelList="selectedChannelList"
            @onSelectedChannel="getSelectedChannel"
          ></Channel>

          <div class="limit-box">
            <div class="left">
              <span class="title">是否限价</span>
              <span class="value" style="">(当前限价： {{ itemInfo?.limitPrice / 100 }} / 座)</span>
            </div>
            <div class="right">
              <a-switch v-model:checked="checked" :disabled="disabled" />
            </div>
          </div>
        </div>
      </div>
    </a-modal>

    <orderModal
      ref="orderDetailModelRef"
      @refresh="getList"
      @ImagePreview="PreviewModal"
      :width="1000"
    ></orderModal>
    <div class="searchBox">
      <a-form ref="formRef" layout="inline" :model="formState" class="formClass">
        <a-form-item label="订单号" name="orderNumber">
          <a-input v-model:value="formState.orderNumber" placeholder="订单号" />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" style="border-radius: 6px" @click="search">搜索</a-button>
          <a-button @click="reset" style="border-radius: 6px">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <a-table
      style="overflow-x: scroll"
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="changePage"
      rowKey="id"
      size="small"
      :scroll="{ x: 100 }"
    >
      <template #emptyText>
        <a-empty description="暂无数据" />
      </template>

      <template #headerCell="{ column }">
        <template v-if="column.key === 'id'">
          <span>id</span>
        </template>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'id'">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '140px' }">
            <a-descriptions-item label="ID">{{ record.id }}</a-descriptions-item>
            <a-descriptions-item label="订单号">
              {{ record.orderNumber }}
            </a-descriptions-item>
            <a-descriptions-item label="倒计时">
              <div style="color: red">
                <CountdownTime
                  :end-time="getEndTime(record.createTime)"
                  @expired="handleExpired(record.id)"
                ></CountdownTime>
              </div>
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-if="column.key === 'filmImg'">
          <img :src="record.filmImg" alt="" style="width: 80px; border-radius: 5px" />
        </template>

        <template v-else-if="column.key === 'filmName'">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
            <a-descriptions-item label="电影名称">
              {{ record.filmName }}
            </a-descriptions-item>
            <a-descriptions-item label="开场时间">
              {{ timeFormat(record.showTime) }}
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'filmData'">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
            <a-descriptions-item label="城市">
              {{ record.city }}
            </a-descriptions-item>
            <a-descriptions-item label="影院">
              <a-tooltip placement="top">
                <template #title>
                  {{ record.cinemaName || '-' }}
                </template>
                <span class="hiddenText">{{ record.cinemaName || '-' }}</span>
              </a-tooltip>
            </a-descriptions-item>
            <a-descriptions-item label="地址">
              <a-tooltip placement="top">
                <template #title>
                  {{ record.cinemaAddress || '-' }}
                </template>
                <span class="hiddenText">{{ record.cinemaAddress || '-' }}</span>
              </a-tooltip>
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'SeatData'">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
            <a-descriptions-item label="影厅">
              {{ record.showName }}
            </a-descriptions-item>
            <a-descriptions-item label="座位">
              {{ record.seatNos }}
            </a-descriptions-item>
            <a-descriptions-item label="数量">
              {{ record.seatCount }}
            </a-descriptions-item>
          </a-descriptions>
        </template>
        <template v-else-if="column.key === 'price'">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
            <a-descriptions-item label="原价">
              ￥{{ toYuan(record.originalPrice) }}
            </a-descriptions-item>
            <a-descriptions-item label="结算价">
              ￥{{ toYuan(record.finalPrice) }}
            </a-descriptions-item>
            <a-descriptions-item label="订单结算">
              ￥{{ toYuan(record.orderFinalPrice) }}
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'action'">
          <div>
            <div style="display: flex; flex-direction: column">
              <a-button
                :disabled="getEndTime(record.createTime) <= new Date().getTime()"
                type="link"
                @click="orderDetailModelRefOpen(record)"
              >
                上传票码
              </a-button>
              <a-button
                :disabled="getEndTime(record.createTime) <= new Date().getTime()"
                type="link"
                style="margin-left: 5px"
                @click="cancelOrder(record)"
              >
                放弃出票
              </a-button>
              <a-button
                :disabled="true"
                type="link"
                style="margin-left: 5px"
                @click="PayModelRefOpen(record)"
              >
                选渠道提交
              </a-button>
            </div>
          </div>
        </template>
      </template>
    </a-table>
  </a-card>
  <ChongMoney ref="ChongMoneyRef" @refresh="getList"></ChongMoney>
  <Recharge ref="rechargeRef" @refresh="getList"></Recharge>
</template>

<style lang="less" scoped>
//支付出票弹框的样式
.pay-modal {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;

  .info-data {
    // width: 445px;
    padding: 4px 20px;
    // background-color: aqua;
    height: 395px;
  }

  .channel-box {
    display: flex;
    flex-direction: column;
    flex: 1;
  }

  .limit-box {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin: 15px 0;
    padding-left: 12px;

    .left {
      .title {
        font-size: 14px;
        font-weight: bold;
        margin-left: 5px;
      }

      .value {
        margin-left: 15px;
        font-size: 14px;
        font-weight: bold;
        color: #ed1a23;
      }
    }
  }
}

.cancel-ipt-container {
  display: flex;
  align-items: center;
  justify-content: center;
}
.hiddenText {
  display: inline-block;
  width: 170px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.aTag-seatNo:nth-child(n + 2) {
  margin-top: 3px;
}
.formClass {
  :nth-child(1) {
    margin-bottom: 2px;
  }
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}

.imgBox {
  width: 50px;
  height: 50px;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 300px;
  img {
    width: 100%;
  }
}

.robitStatusClass {
  text-align: center;
}
</style>
